// mcp-tools.js - MCP工具定义和处理函数
const analyze = require('./analyze.js');
const { writeDebugLog, writeErrorLog } = require('./logging-utils.js');
const { createErrorResponse, createSuccessResponse, createTextResponse } = require('./response-utils.js');

/**
 * 检测现有配置服务
 * @returns {Promise<string|null>} - 现有服务的URL，如果没有则返回null
 */
async function detectExistingConfigServer() {
    const http = require('http');
    const https = require('https');

    // 检查常用的配置服务器端口范围
    const commonPorts = [37251, 37252, 37253, 37254, 37255, 3000, 3001, 8080, 8081];

    for (const port of commonPorts) {
        try {
            const isRunning = await checkConfigServerHealth(port);
            if (isRunning) {
                return `http://127.0.0.1:${port}`;
            }
        } catch (error) {
            // 端口不可用，继续检查下一个
            continue;
        }
    }

    return null;
}

/**
 * 检查配置服务器健康状态
 * @param {number} port - 端口号
 * @returns {Promise<boolean>} - 服务器是否正在运行
 */
async function checkConfigServerHealth(port) {
    return new Promise((resolve) => {
        const http = require('http');
        const options = {
            hostname: '127.0.0.1',
            port: port,
            path: '/health',
            method: 'GET',
            timeout: 2000
        };

        const req = http.request(options, (res) => {
            let data = '';
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on('end', () => {
                try {
                    if (res.statusCode === 200) {
                        const healthData = JSON.parse(data);
                        // 检查是否是我们的配置服务器
                        if (healthData.status === 'ok' && healthData.version) {
                            resolve(true);
                        } else {
                            resolve(false);
                        }
                    } else {
                        resolve(false);
                    }
                } catch (error) {
                    resolve(false);
                }
            });
        });

        req.on('error', () => {
            resolve(false);
        });

        req.on('timeout', () => {
            req.destroy();
            resolve(false);
        });

        req.end();
    });
}

/**
 * 包装异步函数调用，处理错误
 * @param {Function} fn - 要调用的函数
 * @param {Array} args - 函数参数
 * @returns {Promise<Object>} - MCP响应
 */
async function wrapAsyncFunction(fn, ...args) {
    try {
        writeDebugLog('Executing wrapped async function', 'DEBUG', {
            functionName: fn.name || 'anonymous',
            argsCount: args.length,
            argsTypes: args.map(arg => typeof arg)
        });

        const result = await fn(...args);

        writeDebugLog('Async function executed successfully', 'DEBUG', {
            functionName: fn.name || 'anonymous',
            resultType: typeof result
        });

        return createSuccessResponse(result);
    } catch (error) {
        writeErrorLog('Error in wrapAsyncFunction', error, {
            functionName: fn.name || 'anonymous',
            args: args.map((arg, index) => ({
                index,
                type: typeof arg,
                value: typeof arg === 'string' && arg.length > 100 ? arg.substring(0, 100) + '...' : arg
            }))
        });
        return createErrorResponse(error?.message || error || 'Unknown error');
    }
}

/**
 * 处理图像分析工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleAnalyzeImage(args) {
    return wrapAsyncFunction(analyze.analyze_image, args.image, args.prompt);
}

/**
 * 处理图像对比工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleCompareImage(args) {
    return wrapAsyncFunction(analyze.compare_image, args.image1, args.image2);
}

/**
 * 处理带边界框的图像对比工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleCompareImageWithBoundingBoxes(args) {
    return wrapAsyncFunction(analyze.compare_image_with_bounding_boxes, args.image1, args.image2);
}

/**
 * 处理设计截图分析工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleAnalyzeDesignScreenshot(args) {
    return wrapAsyncFunction(analyze.analyze_design_screenshot, args.image);
}

/**
 * 处理组件层次结构提取工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleExtractComponentHierarchy(args) {
    return wrapAsyncFunction(analyze.extract_component_hierarchy, args.image);
}

/**
 * 处理布局规格获取工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleGetExactLayoutSpecifications(args) {
    return wrapAsyncFunction(analyze.get_exact_layout_specifications, args.image);
}

/**
 * 处理视觉令牌识别工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleIdentifyVisualTokens(args) {
    return wrapAsyncFunction(analyze.identify_visual_tokens, args.image);
}

/**
 * 处理精确设计分析工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleAnalyzeDesignWithPrecision(args) {
    return wrapAsyncFunction(analyze.analyze_design_with_precision, args.image);
}

/**
 * 处理模型列表工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleListModels(args) {
    return wrapAsyncFunction(analyze.list_models);
}

/**
 * 处理模型切换工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleUseModel(args) {
    return wrapAsyncFunction(analyze.use_model, args.model, args.provider);
}

/**
 * 处理服务商模型列表工具调用
 * @param {Object} args - 工具参数
 * @returns {Promise<Object>} - MCP响应
 */
async function handleListProviderModels(args) {
    return wrapAsyncFunction(analyze.list_provider_models, args.provider);
}

/**
 * 获取当前使用的模型信息
 * @returns {Promise<Object>} - MCP响应
 */
async function handleGetCurrentModelInfo() {
    try {
        const fs = require('fs');
        const path = require('path');
        const os = require('os');

        // 获取配置文件路径
        const configDir = path.join(os.homedir(), 'Library', 'Preferences', 'vision-analyzer');
        const configPath = path.join(configDir, 'settings.json');

        if (!fs.existsSync(configPath)) {
            return createSuccessResponse({
                current: {
                    provider: 'unknown',
                    model: 'unknown',
                    status: 'no_config'
                },
                available_providers: [],
                message: '未找到配置文件，请先使用 config_provider 工具进行配置'
            });
        }

        const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
        const currentModel = config.current_provider_model;

        let currentProvider = null;
        let currentModelInfo = null;

        // 解析当前使用的模型
        if (currentModel && currentModel !== 'YOUR_PROVIDER-YOUR_MODEL') {
            // 首先尝试直接匹配模型ID
            for (const [providerName, providerConfig] of Object.entries(config.providers || {})) {
                const model = providerConfig.models?.find(m => m.id === currentModel);
                if (model) {
                    currentProvider = providerName;
                    currentModelInfo = {
                        id: model.id,
                        name: model.name,
                        type: model.type,
                        capabilities: model.capabilities,
                        max_tokens: model.max_tokens,
                        supports_vision: model.supports_vision,
                        enabled: model.enabled
                    };
                    break;
                }
            }

            // 如果直接匹配失败，尝试解析provider-model格式
            if (!currentProvider) {
                const parts = currentModel.split('-');
                const providerName = parts[0];
                const modelId = parts.slice(1).join('-'); // 将剩余部分重新组合为模型ID

                if (config.providers[providerName]) {
                    const model = config.providers[providerName].models?.find(m => {
                        if (typeof m === 'string') {
                            return m === modelId;
                        } else if (m && typeof m === 'object') {
                            return m.id === modelId || m.name === modelId;
                        }
                        return false;
                    });

                    if (model) {
                        currentProvider = providerName;
                        // 标准化模型对象格式
                        if (typeof model === 'string') {
                            currentModelInfo = {
                                id: model,
                                name: model,
                                type: 'vision',
                                capabilities: ['image_analysis'],
                                max_tokens: 8192,
                                supports_vision: true,
                                enabled: true
                            };
                        } else {
                            currentModelInfo = {
                                id: model.id,
                                name: model.name,
                                type: model.type,
                                capabilities: model.capabilities,
                                max_tokens: model.max_tokens,
                                supports_vision: model.supports_vision,
                                enabled: model.enabled
                            };
                        }
                    }
                }
            }
        }

        // 构建可用的服务商信息
        const availableProviders = {};
        for (const [providerName, providerConfig] of Object.entries(config.providers || {})) {
            const enabledModels = providerConfig.models?.filter(m => m.enabled) || [];
            if (enabledModels.length > 0) {
                availableProviders[providerName] = {
                    name: providerName,
                    available: true,
                    models: enabledModels.map(m => ({
                        id: m.id,
                        name: m.name,
                        type: m.type,
                        supports_vision: m.supports_vision,
                        max_tokens: m.max_tokens
                    })),
                    baseUrl: providerConfig.base?.replace(/\/v[0-9]+$/, '/***') || '***'
                };
            }
        }

        const result = {
            current: currentProvider && currentModelInfo ? {
                provider: currentProvider,
                model: currentModelInfo.id,
                model_name: currentModelInfo.name,
                type: currentModelInfo.type,
                capabilities: currentModelInfo.capabilities,
                max_tokens: currentModelInfo.max_tokens,
                supports_vision: currentModelInfo.supports_vision,
                status: 'configured'
            } : {
                provider: 'unknown',
                model: 'unknown',
                status: 'not_configured'
            },
            providers: availableProviders,
            config_version: config.version || '1.0.0'
        };

        return createSuccessResponse(result);
    } catch (error) {
        writeErrorLog('Error in handleGetCurrentModelInfo', error);
        return createErrorResponse(`获取模型信息失败: ${error.message}`);
    }
}



/**
 * 获取当前使用的服务商
 * @returns {string} - 服务商名称
 */
function getCurrentProvider() {
    const currentProviderModel = process.env.current_provider_model;
    if (!currentProviderModel || currentProviderModel === 'YOUR_PROVIDER-YOUR_MODEL') {
        return 'moonshot'; // 默认返回moonshot
    }

    const knownProviders = ['moonshot', 'tencent', 'zai'];
    for (const provider of knownProviders) {
        if (currentProviderModel.startsWith(provider + '-')) {
            return provider;
        }
    }

    return 'moonshot'; // 默认返回moonshot
}

/**
 * 处理提取设计令牌请求
 * @param {Object} args - 参数对象
 * @param {string} args.image - 图片的base64编码字符串或文件路径
 * @returns {Promise<Object>} - MCP响应
 */
async function handleExtractDesignTokens(args) {
    try {
        writeDebugLog('handleExtractDesignTokens called', 'DEBUG', {
            hasArgs: !!args,
            hasImage: !!(args && args.image),
            args: args ? Object.keys(args) : null
        });

        if (!args || !args.image) {
            writeDebugLog('Missing required parameter: image', 'WARN');
            return createErrorResponse('Missing required parameter: image');
        }

        writeDebugLog('Calling extract_design_tokens function', 'DEBUG');
        return wrapAsyncFunction(analyze.extract_design_tokens, args.image);
    } catch (error) {
        writeErrorLog('Error in handleExtractDesignTokens', error, { args });
        return createErrorResponse(`Handler error: ${error.message}`);
    }
}

/**
 * 处理生成设计系统Schema请求
 * @param {Object} args - 参数对象
 * @param {string} args.image - 图片的base64编码字符串或文件路径
 * @returns {Promise<Object>} - MCP响应
 */
async function handleGenerateDesignSystemSchema(args) {
    try {
        writeDebugLog('handleGenerateDesignSystemSchema called', 'DEBUG', {
            hasArgs: !!args,
            hasImage: !!(args && args.image)
        });

        if (!args || !args.image) {
            writeDebugLog('Missing required parameter: image', 'WARN');
            return createErrorResponse('Missing required parameter: image');
        }

        writeDebugLog('Calling generate_design_system_schema function', 'DEBUG');
        return wrapAsyncFunction(analyze.generate_design_system_schema, args.image);
    } catch (error) {
        writeErrorLog('Error in handleGenerateDesignSystemSchema', error, { args });
        return createErrorResponse(`Handler error: ${error.message}`);
    }
}

/**
 * 处理基于设计生成代码请求
 * @param {Object} args - 参数对象
 * @param {string} args.image - 图片的base64编码字符串或文件路径
 * @param {string} args.target_platform - 目标平台
 * @param {string} args.framework - 框架类型
 * @returns {Promise<Object>} - MCP响应
 */
async function handleGenerateCodeFromDesign(args) {
    try {
        writeDebugLog('handleGenerateCodeFromDesign called', 'DEBUG', {
            hasArgs: !!args,
            hasImage: !!(args && args.image),
            targetPlatform: args?.target_platform,
            framework: args?.framework
        });

        if (!args || !args.image) {
            writeDebugLog('Missing required parameter: image', 'WARN');
            return createErrorResponse('Missing required parameter: image');
        }

        const { image, target_platform = 'react', framework = 'tailwind' } = args;

        writeDebugLog('Calling generate_code_from_design function', 'DEBUG', {
            targetPlatform,
            framework
        });

        return wrapAsyncFunction(analyze.generate_code_from_design, image, {
            targetPlatform: target_platform,
            framework
        });
    } catch (error) {
        writeErrorLog('Error in handleGenerateCodeFromDesign', error, { args });
        return createErrorResponse(`Handler error: ${error.message}`);
    }
}

/**
 * 处理根据原型图生成HTML页面请求
 * @param {Object} args - 参数对象
 * @param {string} args.image - 图片的base64编码字符串或文件路径
 * @returns {Promise<Object>} - MCP响应
 */
async function handleGenerateHtmlFromPrototype(args) {
    try {
        writeDebugLog('handleGenerateHtmlFromPrototype called', 'DEBUG', {
            hasArgs: !!args,
            hasImage: !!(args && args.image)
        });

        if (!args || !args.image) {
            writeDebugLog('Missing required parameter: image', 'WARN');
            return createErrorResponse('Missing required parameter: image');
        }

        writeDebugLog('Calling generate_html_from_prototype function', 'DEBUG');
        return wrapAsyncFunction(analyze.generate_html_from_prototype, args.image);
    } catch (error) {
        writeErrorLog('Error in handleGenerateHtmlFromPrototype', error, { args });
        return createErrorResponse(`Handler error: ${error.message}`);
    }
}

// MCP工具定义
const MCP_TOOLS = [
    {
        name: 'analyze_image',
        description: '通用的界面描述接口，允许调用方指定自己的提示语来精确描述自己的识别需求',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' },
                prompt: { type: 'string', description: '分析提示语(可选)', default: '请详细分析这张图片的内容' },
                provider: { type: 'string', description: '指定使用的提供商(可选)' },
                model: { type: 'string', description: '指定使用的模型(可选)' }
            },
            required: ['image']
        },
        handler: handleAnalyzeImage
    },
    {
        name: 'compare_image',
        description: '对比两幅图片的差异，列出所有UI差异，忽略阴影或压缩 artifacts',
        inputSchema: {
            type: 'object',
            properties: {
                image1: { type: 'string', description: '第一张图片的Base64编码数据或文件路径' },
                image2: { type: 'string', description: '第二张图片的Base64编码数据或文件路径' },
                provider: { type: 'string', description: '指定使用的提供商(可选)' },
                model: { type: 'string', description: '指定使用的模型(可选)' }
            },
            required: ['image1', 'image2']
        },
        handler: handleCompareImage
    },
    {
        name: 'compare_image_with_bounding_boxes',
        description: '对比两幅图片的差异并返回边界框坐标，格式为 [[x0,y0,x1,y1]]',
        inputSchema: {
            type: 'object',
            properties: {
                image1: { type: 'string', description: '第一张图片的Base64编码数据或文件路径' },
                image2: { type: 'string', description: '第二张图片的Base64编码数据或文件路径' },
                provider: { type: 'string', description: '指定使用的提供商(可选)' },
                model: { type: 'string', description: '指定使用的模型(可选)' }
            },
            required: ['image1', 'image2']
        },
        handler: handleCompareImageWithBoundingBoxes
    },
    {
        name: 'analyze_design_screenshot',
        description: '分析设计截图，返回详细的UI元素描述，包括精确的位置、尺寸、颜色等信息',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' },
                provider: { type: 'string', description: '指定使用的提供商(可选)' },
                model: { type: 'string', description: '指定使用的模型(可选)' }
            },
            required: ['image']
        },
        handler: handleAnalyzeDesignScreenshot
    },
    {
        name: 'extract_component_hierarchy',
        description: '提取组件层次结构，描述元素之间的包含关系',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' },
                provider: { type: 'string', description: '指定使用的提供商(可选)' },
                model: { type: 'string', description: '指定使用的模型(可选)' }
            },
            required: ['image']
        },
        handler: handleExtractComponentHierarchy
    },
    {
        name: 'get_exact_layout_specifications',
        description: '获取精确的布局规格，包括间距、对齐方式等',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' },
                provider: { type: 'string', description: '指定使用的提供商(可选)' },
                model: { type: 'string', description: '指定使用的模型(可选)' }
            },
            required: ['image']
        },
        handler: handleGetExactLayoutSpecifications
    },
    {
        name: 'identify_visual_tokens',
        description: '识别设计令牌，如颜色、字体、圆角等',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' },
                provider: { type: 'string', description: '指定使用的提供商(可选)' },
                model: { type: 'string', description: '指定使用的模型(可选)' }
            },
            required: ['image']
        },
        handler: handleIdentifyVisualTokens
    },
    {
        name: 'analyze_design_with_precision',
        description: '返回精确的设计分析，避免任何模糊描述',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' },
                provider: { type: 'string', description: '指定使用的提供商(可选)' },
                model: { type: 'string', description: '指定使用的模型(可选)' }
            },
            required: ['image']
        },
        handler: handleAnalyzeDesignWithPrecision
    },
    {
        name: 'list_models',
        description: '列出当前LLM服务可用的视觉大模型列表',
        inputSchema: {
            type: 'object',
            properties: {},
            required: []
        },
        handler: handleListModels
    },
    {
        name: 'use_model',
        description: '选定MCP用来解释图片的模型',
        inputSchema: {
            type: 'object',
            properties: {
                model: { type: 'string', description: '模型ID' },
                provider: { type: 'string', description: '指定服务商(可选)' },
                test_with_sample: { type: 'boolean', description: '是否用示例图片测试模型', default: false }
            },
            required: ['model']
        },
        handler: handleUseModel
    },
    {
        name: 'list_provider_models',
        description: '列出指定provider的所有可用模型',
        inputSchema: {
            type: 'object',
            properties: {
                provider: { type: 'string', description: '服务商名称' }
            },
            required: ['provider']
        },
        handler: handleListProviderModels
    },
    {
        name: 'get_current_model_info',
        description: '获取当前使用的模型信息，包括服务商、模型名称、能力等详细信息',
        inputSchema: {
            type: 'object',
            properties: {},
            required: []
        },
        handler: handleGetCurrentModelInfo
    },
    {
        name: 'get_current_config',
        description: '获取当前使用的服务商和模型信息',
        inputSchema: {
            type: 'object',
            properties: {},
            required: []
        },
        handler: async () => {
            try {
                const ConfigManager = require('./config-manager');
                const configManager = new ConfigManager(require('path').resolve(__dirname, '.'));
                const config = configManager.jsonConfigManager.loadConfig();
                const status = await configManager.getConfigurationStatus(false);

                // 从 current_provider_model 推导出 current_provider
                let derivedProvider = 'unknown';
                if (config.current_provider_model && config.current_provider_model !== 'YOUR_PROVIDER-YOUR_MODEL') {
                    // 首先尝试解析provider-model格式 (这是主要格式)
                    const parts = config.current_provider_model.split('-');
                    const providerName = parts[0];
                    const modelId = parts.slice(1).join('-'); // 将剩余部分重新组合为模型ID

                    if (config.providers[providerName]) {
                        // 检查模型是否存在（支持字符串和对象格式）
                        const model = config.providers[providerName].models?.find(m => {
                            if (typeof m === 'string') {
                                return m === modelId;
                            } else if (m && typeof m === 'object') {
                                return m.id === modelId || m.name === modelId;
                            }
                            return false;
                        });

                        if (model) {
                            derivedProvider = providerName;
                        }
                    }

                    // 如果解析失败，再尝试直接匹配模型ID
                    if (derivedProvider === 'unknown') {
                        for (const [providerName, providerConfig] of Object.entries(config.providers || {})) {
                            const model = providerConfig.models?.find(m => {
                                if (typeof m === 'string') {
                                    return m === config.current_provider_model;
                                } else if (m && typeof m === 'object') {
                                    return m.id === config.current_provider_model;
                                }
                                return false;
                            });
                            if (model) {
                                derivedProvider = providerName;
                                break;
                            }
                        }
                    }
                }

                return createSuccessResponse({
                    current_provider: config.current_provider || derivedProvider,
                    current_provider_model: config.current_provider_model || 'unknown',
                    providers: config.providers || {},
                    is_configured: status.isConfigured,
                    configured_providers: status.configuredProviders || [],
                    config_version: config.version || '1.0.0'
                });
            } catch (error) {
                writeErrorLog('Error in get_current_config handler', error);
                return createErrorResponse(`获取配置失败: ${error.message}`);
            }
        }
    },
    {
        name: 'config_status',
        description: '查看当前配置状态，包括已配置的服务商和需要完善的部分',
        inputSchema: {
            type: 'object',
            properties: {
                validateApi: { type: 'boolean', description: '是否进行真实API验证（实际调用API验证密钥有效性），默认false' }
            },
            required: []
        },
        handler: async (args) => {
            const ConfigManager = require('./config-manager');
            const configManager = new ConfigManager(require('path').resolve(__dirname, '.'));
            const status = await configManager.getConfigurationStatus(args.validateApi || false);
            const report = await configManager.generateConfigurationReport(status);
            return createTextResponse(report);
        }
    },
    {
        name: 'config_provider',
        description: '启动Web配置界面，通过浏览器配置LLM服务商的API密钥',
        inputSchema: {
            type: 'object',
            properties: {},
            required: []
        },
        handler: async () => {
            try {
                const WebConfigServer = require('./web-config-server');
                const projectRoot = require('path').resolve(__dirname, '.');
                const webServer = new WebConfigServer(projectRoot);

                // 首先检测是否有现有的配置服务正在运行
                const existingServerUrl = await detectExistingConfigServer();

                if (existingServerUrl) {
                    // 发现现有服务，直接打开浏览器
                    webServer.openBrowser(existingServerUrl);

                    const configMessage = `🌐 检测到现有配置服务

已发现正在运行的配置服务，已在浏览器中打开:
${existingServerUrl}

💡 说明:
• 检测到端口 ${new URL(existingServerUrl).port} 上已有配置服务运行
• 为避免端口冲突，直接使用现有服务
• 所有配置更改都会保存到同一份配置文件

💡 支持的服务商:
• 智谱AI (Zai) - glm-4.5v
• Moonshot - moonshot-v1系列视觉模型
• 腾讯混元 - hunyuan-vision系列
• 自定义 - 兼容OpenAI API格式的服务商

配置完成后请重新启动Vision Analyzer以应用更改。`;

                    return createTextResponse(configMessage);
                }

                // 没有现有服务，尝试启动新服务
                const url = await webServer.start();
                webServer.openBrowser(url);

                const configMessage = `🌐 Web配置界面已启动

请在浏览器中打开以下地址完成配置:
${url}

💡 支持的服务商:
• 智谱AI (Zai) - glm-4.5v
• Moonshot - moonshot-v1系列视觉模型
• 腾讯混元 - hunyuan-vision系列
• 自定义 - 兼容OpenAI API格式的服务商

配置完成后请重新启动Vision Analyzer以应用更改。`;

                return createTextResponse(configMessage);

            } catch (error) {
                // 如果是端口冲突错误，尝试查找现有服务
                if (error.code === 'EADDRINUSE' || error.message.includes('already in use')) {
                    const existingServerUrl = await detectExistingConfigServer();

                    if (existingServerUrl) {
                        // 简单打开浏览器，不需要WebConfigServer实例
                        const { exec } = require('child_process');
                        const platform = process.platform;
                        let command;

                        switch (platform) {
                            case 'darwin':
                                command = `open "${existingServerUrl}"`;
                                break;
                            case 'win32':
                                command = `start "" "${existingServerUrl}"`;
                                break;
                            default:
                                command = `xdg-open "${existingServerUrl}"`;
                                break;
                        }

                        exec(command, (execError) => {
                            if (execError) {
                                writeDebugLog('无法自动打开浏览器', 'WARN', {
                                    error: execError.message,
                                    url: existingServerUrl
                                });
                            } else {
                                writeDebugLog('✅ 已在浏览器中打开现有配置服务', 'INFO');
                            }
                        });

                        const fallbackMessage = `🌐 端口冲突，已连接到现有配置服务

检测到端口冲突，但发现了正在运行的配置服务:
${existingServerUrl}

已在浏览器中打开配置界面。

💡 说明:
• 新服务启动时遇到端口冲突
• 自动连接到现有的配置服务
• 所有配置更改都会保存到同一份配置文件

💡 支持的服务商:
• 智谱AI (Zai) - glm-4.5v
• Moonshot - moonshot-v1系列视觉模型
• 腾讯混元 - hunyuan-vision系列
• 自定义 - 兼容OpenAI API格式的服务商

配置完成后请重新启动Vision Analyzer以应用更改。`;

                        return createTextResponse(fallbackMessage);
                    }
                }

                // 其他错误，抛出原始错误
                throw error;
            }
        }
    },
    {
        name: 'provider_info',
        description: '获取服务商的注册链接和基本信息',
        inputSchema: {
            type: 'object',
            properties: {
                providerName: { type: 'string', description: '服务商名称: moonshot, tencent, zai', enum: ['moonshot', 'tencent', 'zai'] }
            },
            required: ['providerName']
        },
      handler: async (args) => {
            const ConfigManager = require('./config-manager');
            const configManager = new ConfigManager(require('path').resolve(__dirname, '.'));
            const providerInfo = configManager.getProviderInfo(args.providerName);
            if (providerInfo) {
                const infoText = [
                    `📋 ${providerInfo.name}`,
                    '',
                    `📝 描述: ${providerInfo.description}`,
                    '',
                    `🔗 注册地址: ${providerInfo.signupUrl}`,
                    `💰 价格信息: ${providerInfo.pricingUrl}`,
                    '',
                    '💡 使用提示:',
                    '1. 访问注册地址完成账号注册',
                    '2. 获取API密钥',
                    '3. 使用 config_provider 工具配置API密钥'
                ].join('\n');
                return createTextResponse(infoText);
            } else {
                return createTextResponse(`找不到服务商 ${args.providerName} 的信息`);
            }
        }
    },
    {
        name: 'extract_design_tokens',
        description: '提取设计令牌 - 基于Design Tokens方法论的系统化设计分析',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' }
            },
            required: ['image']
        },
        handler: handleExtractDesignTokens
    },
    {
        name: 'generate_design_system_schema',
        description: '生成设计系统JSON Schema - 为Design Tokens提供结构化约束',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' }
            },
            required: ['image']
        },
        handler: handleGenerateDesignSystemSchema
    },
    {
        name: 'generate_code_from_design',
        description: '基于设计令牌生成代码 - 技术中立的代码生成',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' },
                target_platform: { type: 'string', description: '目标平台 (react, vue, flutter, html等)', default: 'react' },
                framework: { type: 'string', description: '框架类型 (tailwind, bootstrap, material等)', default: 'tailwind' }
            },
            required: ['image']
        },
        handler: handleGenerateCodeFromDesign
    },
    {
        name: 'generate_html_from_prototype',
        description: '根据原型图生成HTML页面初始版本 - 使用像素级精确的UI实现',
        inputSchema: {
            type: 'object',
            properties: {
                image: { type: 'string', description: 'Base64编码的图像数据' }
            },
            required: ['image']
        },
        handler: handleGenerateHtmlFromPrototype
    }
  ];

module.exports = {
    MCP_TOOLS,
    wrapAsyncFunction,
    handleAnalyzeImage,
    handleCompareImage,
    handleCompareImageWithBoundingBoxes,
    handleAnalyzeDesignScreenshot,
    handleExtractComponentHierarchy,
    handleGetExactLayoutSpecifications,
    handleIdentifyVisualTokens,
    handleAnalyzeDesignWithPrecision,
    handleListModels,
    handleUseModel,
    handleListProviderModels,
    getCurrentProvider,
    handleGenerateHtmlFromPrototype
};